package leetcode


fun main(args: Array<String>) {
    println(RomantoInt().advancedVersion("LVIII"))
}

class RomantoInt {
    val romanMap = mapOf(
            Pair('I', 1),
            Pair('V', 5),
            Pair('X', 10),
            Pair('L', 50),
            Pair('C', 100),
            Pair('D', 500),
            Pair('M', 1000)
    )

    /**
     * 遇到左边比右边小的，那么减去左边这个符号代表的数值，反之加上这个数值 并且此数值作为基准数值继续向前比较
     */
    fun romanToInt(s: String): Int {
        if (s.length == 1) return romanMap.getValue(s[0])
        var sum = 0
        var i = s.length - 1
        var base = romanMap[s[i]]!!
        sum += base
        var extra = 0
        while (i >= 0) {
            extra = romanMap[s[i]]!!
            if (extra < base) {
                sum -= extra
            } else {
                base = extra
                sum += extra
            }
            i--
        }
        return sum
    }

    //改进细节
    fun advancedVersion(s: String): Int {
        var sum = 0
        var base = 0 //用零作为基准数值
        var extra = 0
        var i = s.length - 1
        while (i >= 0) {
            extra = romanMap[s[i]]!!
            if (extra >= base) {
                base = extra
                sum += extra
            } else sum -= extra

            i--
        }
        return sum
    }
}